//
//  YCLoginManager.m
//  HeartWorldClient
//
//  Created by 董知樾 on 2017/7/13.
//  Copyright © 2017年 谭明权. All rights reserved.
//

#import "YCLoginManager.h"
#import <CoreLocation/CoreLocation.h>


@interface YCLoginManager ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *mgr;

@end

@implementation YCLoginManager

static YCLoginManager *_manager;

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[YCLoginManager alloc] init];
    });
}

+ (instancetype)shareManager {
    return _manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.mgr = [CLLocationManager new];
        //判断能否响应对应的方法
        if ([self.mgr respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.mgr requestWhenInUseAuthorization];
        }
        self.mgr.delegate = self;
        //4. 开始定位
        [self.mgr startUpdatingLocation];
        
        
        self.phoneNumber = [[NSUserDefaults standardUserDefaults] objectForKey:KLINKMOBILE];
    }
    return self;
}

//MARK:~~~~ CLLocationManagerDelegate ~~~~
//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//    
//    CLLocation *location = locations.lastObject;
//    
//    _latPoint = @(location.coordinate.latitude).stringValue;
//    
//    _lngPoint = @(location.coordinate.longitude).stringValue;
//    
//    [self.mgr stopUpdatingLocation];
//    
//}


- (void)getVerifyCode:(YCLoginManagerVerifyBlock)complete {
    NSString *url =[YCUrlManger sharedYCUrlManger].getSmsVoiceVerifyCodeUrl;

    NSDictionary *params =@{
                            @"link_phone":self.phoneNumber,//    手机号码
                            @"sms_type":@"0",      //验证码类型   0 短信  1 语音
                            @"post_ip":[YCCommonTool getIPAddress],       //当前机器的ip地址
                            @"client_id":@"1"       //客户端分类 1-心脑管家
                            };
    
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {
        
//        LJXLog(@"验证码是:%@",json[@"Msg"]);
        if ([[json allKeys] containsObject:@"phone_code"]){
            complete(YES, @"已发送！");
            NSLog(@"验证码是---%@",json[@"phone_code"]);
            if ([self.phoneNumber isEqualToString:@"13810534048"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"verify_code_noti" object:json[@"phone_code"]];
            }
        }
        
        if([json[@"Code"] isEqualToString:@"9004"]){
            
            complete(NO, @"你的语音短信过期了！");
        }
        
        if([json[@"Code"] isEqualToString:@"9001"]){
            
            complete(NO, @"短信通道出错！");
        }
        
    } failure:^(NSError *error) {
        complete(NO, error.localizedDescription);
    }];

    
}
- (void)getVoiceVerifyCode:(YCLoginManagerVerifyBlock)complete {
    NSString *url =[YCUrlManger sharedYCUrlManger].getSmsVoiceVerifyCodeUrl;
    
    NSDictionary *params = @{
                            @"link_phone":self.phoneNumber,//    手机号码
                            @"sms_type":@"1",      //验证码类型   0 短信  1 语音
                            @"post_ip":[YCCommonTool getIPAddress],       //当前机器的ip地址
                            @"client_id":@"1"       //客户端分类 1-心脑管家
                            };
    
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {
        
        if ([[json allKeys] containsObject:@"phone_code"]){
            complete(YES, @"已发送！");
            NSLog(@"验证码是---%@",json[@"phone_code"]);
        }
        
        
    } failure:^(NSError *error) {
        complete(NO, error.localizedDescription);
    }];
}


- (void)verifyCodeLoginWithCode:(NSString *)code success:(YCLoginManagerLoginSuccessBlock)success failure:(YCLoginManagerLoginFailureBlock)failure {
    //1.app_member_op/login_code.aspx 验证码登陆或注册
    NSString *url = [YCUrlManger sharedYCUrlManger].verifyCodeLoginUrl;
    NSString* latitube = [YCUserManager sharedYCUserManager].latitude;
    NSString* longitude = [YCUserManager sharedYCUserManager].longitude;
    NSDictionary *params = @{
                             @"member_mobile":self.phoneNumber,
                             @"phone_code":code,
                             @"yw_id":yw_id,
                             @"phone_id":[[STISystemInfo deviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""],
                             @"lat_point":latitube ?: @"",
                             @"lng_point":longitude ?: @"",
                             };
    
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {

        if ([[json allKeys] containsObject:@"member_id"]) {
            success(json[@"member_id"]);

        } else {
//            NSString *error_code = json[@"error_code"];
            failure(@"验证失败！请重试");
        }
        
    } failure:^(NSError *error) {
        failure(@"验证失败！请重试");
    }];
    
}
- (void)accountPasswordLoginWithPassword:(NSString *)password success:(YCLoginManagerLoginSuccessBlock)success failure:(YCLoginManagerLoginFailureBlock)failure {
    
    NSString *url = [YCUrlManger sharedYCUrlManger].passwordLoginUrl;
    NSDictionary *params = @{
                             @"member_mobile":self.phoneNumber,
                             @"member_pwd":password,
                             @"yw_id":yw_id,
                             @"visit_id":[[STISystemInfo deviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""]
                             };
    
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {
        NSString *member_id = json[@"member_id"];
        if (member_id.length) {
            success(member_id);
        } else {
            failure(@"账号或密码错误，请重新输入，建议使用手机号快捷登录");
        }
        
    } failure:^(NSError *error) {
        failure(@"账号或密码错误，请重新输入，建议使用手机号快捷登录");
    }];
    
}

- (void)verifyCodeVerifyWithCode:(NSString *)code complete:(YCLoginManagerVerifyBlock)complete {
    
    NSString *url = [YCUrlManger sharedYCUrlManger].verifyCodeVerifyUrl;
    NSDictionary *params = @{
                             @"member_mobile":self.phoneNumber,
                             @"phone_code":code
                             };
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {
        if ([json[@"error_code"] isEqualToString:@"ok"]) {
            
            complete(YES, @"成功");
        } else {
            complete(NO, @"失败");
        }
        
    } failure:^(NSError *error) {
        complete(NO, error.localizedDescription);
    }];
}

- (void)resetPassword:(id)params complete:(YCLoginManagerVerifyBlock)complete {
    NSString *url = [YCUrlManger sharedYCUrlManger].resetPasswordUrl;

    
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {
        if ([json[@"error_code"] isEqualToString:@"ok"]) {
            
            complete(YES, @"成功");
        } else {
            complete(NO, @"失败");
        }
        
    } failure:^(NSError *error) {
        complete(NO, error.localizedDescription);
    }];
}

- (void)loginSuccessConfigMemberId:(NSString *)memberId {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:memberId forKey:KEXPERTID];
    [def setObject:_phoneNumber forKey:KLINKMOBILE];
    [def synchronize];
    [YCUserTool sharedTools].expertID = [[NSUserDefaults standardUserDefaults]objectForKey:KEXPERTID];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
    
//    //给后后台发送极光推送信息
//    [DownloadData sendregisterID];//不要删，重要
//    
//    //app端爱心百倍卡各种销售类型
//    [DownloadData  requestInfolistData];//不要删，非常重要
//    
    
//    NSString *em_userId = [NSString stringWithFormat:@"%@_%@",memberId,yw_id];
//    [YCtool EMClientLoginWithUserId:em_userId];
//    
    [def synchronize];
}

- (void)accountIsExistPhoneNumber:(NSString *)phoneNumber complete :(YCLoginManagerVerifyBlock)complete {
    NSString *url =[YCUrlManger sharedYCUrlManger].accoutIsExistUrl;
    
    NSDictionary *params = @{
                             @"member_mobile":phoneNumber//    手机号码
                             };
    
    [DownloadData post:url SerializerType:YCRequestSerializerTypeJSON params:params success:^(id json) {
        
        if ([json[@"error_code"] isEqualToString:@"yes"]) {
            
            complete(YES, @"成功");
        }else if ([json[@"error_code"] isEqualToString:@"no"]){
            complete(NO, @"该手机号没有注册过");
        }else {
            complete(NO, @"失败");
        }
        
        
    } failure:^(NSError *error) {
        complete(NO, error.localizedDescription);
    }];
}

@end
